// https://www.lintcode.com/problem/remove-linked-list-elements/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: a ListNode
     * @param val: An integer
     * @return: a ListNode
     */
    public ListNode removeElements(ListNode head, int val) {
        // write your code here
        ListNode new_head = null, new_tail = null;
        while (head != null) {
            if (head.val != val) {
                if (null == new_head) {
                    new_head = head;
                    new_tail = head;
                }
                else {
                    new_tail.next = head;
                    new_tail = new_tail.next;
                }
                head = head.next;
                new_tail.next = null;
            }
            else {
                head = head.next;
            }
        }
        return new_head;
    }
}